package com.myzl.stream.config;

import com.myzl.stream.util.ffmpeg.FfmpegUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author cew
 */
@Slf4j(topic = "admin-steam")
@Component
public class StreamGobbler {


    /**
     * 异步开启新的线程池
     * @param is ffmpeg输入的错误流
     * @param type 类型
     * @param videoUrl 推流地址
     */
    @Async("threadPoolTaskExecutor")
    public void run(InputStream is, String type, String videoUrl) {
        try {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                // 增加不续期取消推流
                if (type.equals("Error")) {
                    if (FfmpegUtil.exists(videoUrl)){
                        log.info(line);
                    } else {
                        // 视频流不存在了跳出循环
                        log.info("缓存过期，跳出循环");
                        break;
                    }
                } else {
                    log.debug(line);
                }
            }
            // 无论正常还是意外导致跳出循环都应该注销视频流
            FfmpegUtil.destroy(videoUrl);
        } catch (IOException e) {
            log.error("视频流出现异常：",e);
        }
    }
}
